<template>
  <div class="message-page flex flex-column">
    <div class="hospital-info flex">
      <div class="hospital-icon iconfont iconyiyuan" />
      <div class="hospital-name">
        {{ currentDept.hospitalName }} {{ currentDept.departmentName }}
      </div>
    </div>

    <div class="message-box flex1" ref="messageBoxRef">
      <van-list
        finished-text="没有更多了"
        direction="up"
        v-model:loading="pageStatus.loading"
        :finished="pageStatus.allLoaded"
        @load="nextMessage"
      >
        <template v-for="item in messageResulte.data.records" :key="item.articleId">
          <MsgItem :msg-item="item" @updateTrackData="updateTrackData" />
        </template>
      </van-list>
    </div>
  </div>
</template>

<script>
import { reactive, watch, ref, nextTick } from 'vue';
import { useCurrentDeptInfo, useUserInfo } from '@/hooks/store';
import { usePageLoadStatus } from '@/hooks/utils';
import { useService } from '@/utils/services';
import { EMPTY_PAGE_BEAN } from '@/constants/common';
import { RESOURCE_TYPE_NUM } from '@/constants/business';
import XltData from '@/utils/XltData';
import MsgItem from '../consult/components/MsgItem';
import Utils from '@/utils/utils';
import { useStore } from 'vuex';
export default {
  components: { MsgItem },
  setup() {
    const actions = useService();
    const pageParams = reactive({
      currentPage: 1,
      pageSize: 20
    });

    const messageBoxRef = ref(null);

    const store = useStore();

    const branchHospitalId = ref('');
    const departmentId = ref('');
    const largeDepartmentId = ref('');
    const hosEmployeeId = ref('');
    const hosEmployeeName = ref('');

    const currentDept = useCurrentDeptInfo();
    const userInfo = useUserInfo();

    const messageResulte = reactive({
      data: EMPTY_PAGE_BEAN
    });

    const pageStatus = usePageLoadStatus(messageResulte);

    function trackData(messageType, messageId) {
      const { global } = store.state;
      let sensors = {
        gender: global.userInfo.sex, //性别
        hospital: global.userInfo.hospitalId, //所在医院
        subHospital: branchHospitalId.value, //所在分院
        department: largeDepartmentId.value, //所在科室（大科室）
        ward: departmentId.value, //所在病区（小科室）
        patientsId: userInfo.value.patientsId, //用户id
        hosEmployeeId: hosEmployeeId.value, //医护id
        hosEmployeeName: hosEmployeeName.value, //医护名称
        messageType: messageType, //消息类型
        messageId: messageId,
        getMessageTime: Utils.date2string(null, '-', true) //查看时间
      };
      XltData.track('getMessage', sensors);
    }

    function updateTrackData(type, messageId) {
      // trackData(type, messageId);
    }

    function getMessageList() {
      actions.hos
        .getInquiryMessageList({
          ...pageParams,
          patientId: userInfo.value.patientsId,
          orgId: currentDept.value.departmentId
        })
        .then((data) => {
          //埋点
          branchHospitalId.value = data.branchHospitalId;
          departmentId.value = data.departmentId;
          largeDepartmentId.value = data.largeDepartmentId;
          if (data.responseIpage.records && data.responseIpage.records.length > 0) {
            hosEmployeeId.value = data.responseIpage.records[0].employeeId;
            hosEmployeeName.value = data.responseIpage.records[0].employeeName;
            data.responseIpage.records.forEach((item) => {
              if (item.resourceType == 8) {
                // trackData('图文', item.messageId);
              }
            });
          }

          data.responseIpage.records.reverse();
          if (data.responseIpage.current != 1) {
            messageResulte.data = {
              ...data.responseIpage,
              records: [...data.responseIpage.records, ...messageResulte.data.records]
            };
          } else {
            messageResulte.data = data.responseIpage;
            scrollBottom();
          }
          messageHaveRead(data?.responseIpage?.records || []);
        });
    }

    function messageHaveRead(messageList) {
      let message = messageList.filter(filterMessage).map((item) => ({
        planDetailId: item.detailsId,
        planType: item.messageFromtype,
        messageId: item.messageId
      }));
      message.length && actions.hos.messageHaveRead({ message });
    }

    function filterMessage(item) {
      return (
        [RESOURCE_TYPE_NUM.IMAGE_TEXT, RESOURCE_TYPE_NUM.AUDIO, RESOURCE_TYPE_NUM.VIDEO].includes(
          item.resourceType
        ) &&
        !item.patientsReadStatus &&
        !!item.messageFromtype
      );
    }

    function nextMessage() {
      pageParams.currentPage += 1;
      getMessageList();
    }

    function scrollBottom() {
      setTimeout(() => {
        nextTick(() => {
          messageBoxRef.value.scrollTop = 10000000;
        });
      }, 500);
    }

    watch(
      () => [currentDept.value.departmentId, userInfo.value.patientsId],
      () => {
        if (currentDept.value.departmentId && userInfo.value.patientsId) {
          getMessageList(currentDept.value.departmentId);
        }
      },
      {
        immediate: true
      }
    );
    return {
      currentDept,
      pageStatus,
      messageResulte,
      nextMessage,
      messageBoxRef,
      updateTrackData,
      trackData
    };
  }
};
</script>

<style lang="scss" scoped>
.message-page {
  background: #fff;
  height: 100vh;

  .message-box {
    background: #f7f7fa;
    padding: 32px;
    overflow-y: auto;
    border-radius: 60px 60px 0 0;
  }

  .message-tools {
    padding: 0 32px;
    .message-input-box {
      padding: 20px 0;
    }

    .message-input {
      margin-right: 22px;
      width: 552px;
      height: 72px;
      background: #f7f7fa;
      border: 0;
      border-radius: 100px;
      padding: 18px 32px;
      font-size: 26px;
      font-weight: 400;
      color: #212121;
    }

    .message-btn {
      width: 112px;
      height: 72px;
      background: #e9e9ed;
      border-radius: 40px;
      font-size: 26px;
      font-weight: 400;
      color: #a2a6b8;
      line-height: 72px;
      text-align: center;
    }

    .file-options {
      padding: 20px 0;

      .file-btn {
        margin-right: 30px;
        font-size: 30px;
        font-weight: 400;
        color: #777b8f;
      }

      .file-icon {
        font-size: 42px;
        margin-right: 10px;
        display: inline-block;
        vertical-align: middle;
      }
    }
  }
}
.hospital-info {
  padding: 24px 32px;
  font-size: 32px;
  font-weight: 500;
  color: #373d52;
  line-height: 44px;

  .hospital-icon {
    margin-right: 12px;
    font-size: 40px;
    color: #fa940f;
  }
}
</style>